<template>
  <div>
    <!-- 摄像机 -->
    <canvas ref="videoCanvas" class="w-full h-full"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";
import { GetImage } from "../../../../../wailsjs/go/api/FileSystem";
import {
  CameraCapture,
} from "../../../../../wailsjs/go/api/CameraApi.js";

onMounted(async () => {
  await initCanvas();
  await startCamera(1); // 启动摄像头1
});

const videoCanvas = ref(null);
const ctx = ref(null);
async function initCanvas() {
  const canvas = videoCanvas.value;
  videoCanvas.value.width = videoCanvas.value.clientWidth;
  videoCanvas.value.height = videoCanvas.value.clientHeight;
  ctx.value = videoCanvas.value.getContext("2d", { willReadFrequently: false });
}

const webSockets = ref({
  ws1: null,
  ws2: null,
});
const cids = ref({
  cid1: "",
  cid2: "",
});

// 打开摄像头
const startCamera = async (id) => {
  if (!id) return;

  webSockets.value[`ws${id}`] = new WebSocket("ws://localhost:8090/ws");
  webSockets.value[`ws${id}`].onmessage = handleMessage; // 接收消息
};

// 关闭摄像头
const stopCamera = async (id) => {
  if (!id) return;
  if (cids.value[`cid${id}`] == "") return;

  // await StartCameraCaptureForClient(cids.value[`cid${id}`]); // 停止摄像头
  // if (
  //   webSockets.value[`ws${id}`] &&
  //   webSockets.value[`ws${id}`].readyState == WebSocket.OPEN
  // ) {
  //   webSockets.value[`ws${id}`].close();
  //   console.log(`关闭摄像头${id}`);
  // }
};

// 接收消息的函数
const handleMessage = (e, id = 1) => {
  console.log("接受的具体信息:", e.data);
  if (typeof e.data == "string") {
    const header = JSON.parse(e.data);
    if (header.type == "ping") {
      cids.value.cid1 = header.cid;
      console.log(`摄像头 cid 为:`, header.cid);
    } else if (header.type == "data") {
      // 处理摄像头数据
      webSockets.value.ws1.binaryType = "arraybuffer"; //下一个消息是二进制视频数据
    }
  } else if (e.data instanceof ArrayBuffer) {
    // 将ArrayBuffer转为Blob
    const blob = new Blob([e.data], { type: "image/jpeg" });
    const imageUrl = URL.createObjectURL(blob);
    renderFrame(imageUrl);
    setTimeout(() => {
      URL.revokeObjectURL(imageUrl);
    }, 100);
  }
};

// 渲染到Canvas
const renderFrame = (imageData) => {
  const img = new Image();

  // 加载状态检查
  if (!img.complete) {
    console.warn("图片尚未加载完成");
    return;
  }

  img.onerror = () => {
    console.error("图片加载失败:", imageData);
    return;
  };

  img.onload = () => {
    if (!videoCanvas.value || !ctx.value) {
      console.error("Canvas上下文未初始化");
      return;
    }

    const canvas = videoCanvas.value;

    // 添加尺寸合法性校验
    if (img.width <= 0 || img.height <= 0) {
      console.warn("无效的图片尺寸:", img.width, img.height);
      return;
    }

    const ratio = Math.min(
      canvas.width / img.width,
      canvas.height / img.height
    );

    // 添加容错判断
    if (isNaN(ratio) || !isFinite(ratio)) {
      console.warn("无效的缩放比例:", ratio);
      return;
    }
    const drawWidth = img.width * ratio;
    const drawHeight = img.height * ratio;
    ctx.value.clearRect(0, 0, canvas.width, canvas.height);
    ctx.value.drawImage(
      img,
      (canvas.width - drawWidth) / 2,
      (canvas.height - drawHeight) / 2,
      drawWidth,
      drawHeight
    );
  };
  img.src = imageData;
};

// 截图
const handleCapturePicture = async (id) => {
  const res = await CameraCapture();
  console.log(res);
  if (res.code === -1) {
    console.log("未识别到正中心人脸");
    return;
  }

  const imageData = await GetImage(res.path);
  setStorageWithEvent("snipaste", {
    path: res.path,
    basePath: `${imageData}`,
    base64Path: `data:image/jpeg;base64,${imageData}`,
  });
  // stopCamera(id);
};

defineExpose({
  startCamera,
  stopCamera,
  handleCapturePicture,
});
</script>

<style scoped lang="scss">
</style>